<?php
declare (strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\Order;
use app\model\Promotion;
use app\util\CacheHelper;
use think\annotation\route\Group;
use think\annotation\Route;
use \app\model\User as UserM;
use app\middleware\CheckAdmin;
use think\annotation\route\Middleware;

/**
 * 登陆
 * Class User
 * @package app\controller\admin
 * @Group("admin/User")
 */
class User extends BaseController
{

    /**
     * 创建用户
     * @Route("createUser", method="POST")
     */
    public function create()
    {
        //接收数据
        $data = [
            'account' => input('account', '', 'trim'),
            'parent_id' => input('parent_id', '', 'trim'),
            'password' => input('password', '', 'trim'),
            'role' => input('role', '-1', 'trim'),
            'user_name' => input('user_name', '', 'trim')
        ];

        if ($data['role'] === 0) {
            return json_error(10004);
        }
        if (empty($data['account'])) {
            return json_error(12007);
        }
        if (empty($data['password'])) {
            return json_error(12008);
        }
        if (empty($data['password'])) {
            return json_error(12014);
        }
        if (strlen($data['password']) != 6) {
            return json_error(12015);
        }
        $data['password'] = encrypt_pass($data['password']);

        $userM = new UserM();
        $oneUser = $userM->where('account', $data['account'])->find();
        if (!empty($oneUser)) {
            return json_error(11109);
        }

        $result = $userM->save($data);
        return json_ok($result, 200);
    }

    /**
     * 修改用户信息
     * @Route("updateUser", method="POST")
     */
    public function update()
    {
        $id =  input('id', '', 'int');
        $user_name = input('user_name', '', 'trim');
        $account = input('account', '', 'trim');
        $password = input('password', '', 'trim');
        $role = input('role', '', 'trim');
        $parent_id = input('parent_id', '', 'trim');

        $user_name && $data['user_name'] = $user_name;
        $account && $data['account'] = $account;
        $password && $data['password'] = encrypt_pass($password);
        $role && $data['role'] = $role;
        $parent_id && $data['parent_id'] = $parent_id;

        if (empty($id)) {
            return json_error(10002);
        }

        $userM = new UserM();
        $user = $userM->where(["id" => $id])->find();
        if (empty($user)) {
            return json_error(10001);
        }

        $oneUser = $userM->where("id" , '<>', $id)->where(['account' => $account])->find();
        if ($oneUser ) {
            return json_error(11109);
        }
        $result = $user->save($data);
        return json_ok($result, 200);
    }

    /**
     * 获取下线
     * @Route("subordinate", method="get")
     * @Middleware({CheckAdmin::class})
     */
    public function getSubordinate()
    {
        $uid =  input('uid', '', 'int');
        if (empty($uid)) {
            return json_error(10002);
        }
        $userM = new UserM();
        $users = $userM->where(["parent_id" => $uid])->field(['user_name,id,account'])->select();
        return json_ok($users, 200);
    }

    /**
     * 生成跟踪码
     * @Middleware({CheckAdmin::class})
     * @Route("makeTrackingCode", method="POST")
     */
    public function  makeTrackingCode()
    {

        $goodsId =  input('goodsId', '', 'int');
        $uid = input('id', '', 'int');
        if (empty($goodsId)) {
            return json_error(10002);
        }
        $trackingCode = makeTrackingCode($goodsId, $uid);
        return json_ok(['trackingCode' => $trackingCode], 200);
    }


    /**
     * 生成推广链接
     * @Route("promotion", method="POST")
     * @Middleware({CheckAdmin::class})
     */
    public function promotion()
    {

        $data = [
            'active_brokerage' => input('activeBrokerage', '', 'trim'),
            'charge_brokerage' => input('chargeBrokerage', '', 'trim'),
            'user_id' => input('subordinateId', '', 'trim'),//下线id
            'goods_id' => input('goodsId', '', 'trim'),//商品id
            'parent_user_id' => input('parent_user_id', '', 'trim'),//id
        ];


        if (empty($data['user_id']) || empty($data['goods_id'])) {
            return json_error(10002);
        }

        $goodsM = new \app\model\Goods();
        $goods = $goodsM->where(['goods_id' => $data['goods_id']])->find();
        if (empty($goods)) {
            return json_error(10018);
        }

        $userM = new UserM();
        $users = $userM->where(["id" => $data['user_id']])->field(['user_name,account'])->find();
        if (empty($users)) {
            return json_error(11104);
        }

        $data['subordinate_name'] = $users['user_name'];
        $data['subordinate_account'] = $users['account'];
        $data['trackingCode'] = makeTrackingCode($data['goods_id'], $data['user_id']);
        $promotionM = new Promotion();
        $promotionM->save($data);

        $reportKey = config('cachekeys.user_report');
        $reportTgKey = config('cachekeys.user_report_tg');
        $reportTgKey = $reportTgKey . $data['user_id'];

        $redis = new CacheHelper();
        $r = $redis->sadd($reportTgKey, $data['goods_id']);

        $jsonData = array(
            'trackCode' => $data['trackingCode'],// 跟踪号
            'goodsType' => -1, // 商品类型
            'orderTotalNum' => 0, // 订单总数
            'yjMoney' => 0, // 佣金金额
        );
        $redis->lpush('tttt', 1);

        $jsonencode = json_encode($jsonData) . '';
        $r2 = $redis->lpush($reportKey, $jsonencode);


        return json_ok(['trackingCode' => $data['trackingCode'], 'sadd' => $r, 'lpush' => $r2, 'pushData' => $jsonencode, 'reportTgKey' => $reportTgKey, 'reportKey' => $reportKey], 200);

    }

    /**
     * 生成推广链接
     * @Route("editPromotion", method="POST")
     */
    public function editPromotion()
    {
        $id =  input('id', '', 'int');
        $user_id = input('subordinateId', '', 'trim');//下线id
        $active_brokerage = input('activeBrokerage', '', 'trim');
        $charge_brokerage = input('chargeBrokerage', '', 'trim');
        if (empty($id)) {
            return json_error(10002);
        }
        $promotionM = new Promotion();
        $onePromotion = $promotionM->where('id', $id)->find();
        if (empty($onePromotion)) {
            return json_error(10004);
        }

        $user_id && $onePromotion->user_id = $user_id;
        $active_brokerage && $onePromotion->active_brokerage = $active_brokerage;
        $charge_brokerage && $onePromotion->charge_brokerage = $charge_brokerage;
        $onePromotion->trackingCode = makeTrackingCode($onePromotion->goods_id, $user_id);
        $onePromotion->save();
        return json_ok(['trackingCode' => $onePromotion->trackingCode], 200);

    }



    /**
     * 获取用户信息
     * @Route("info", method="get")
     * @Middleware({CheckAdmin::class})
     */
    public function info()
    {
        $uid = input('get.uid', '', 'int');
        if (empty($uid)) {
            return json_error(10002);
        }
        $userInfo = $this->request->sys_user;
        if ($uid != $userInfo->id) {
            return json_error(10002);
        }
        unset($userInfo['password']);
        return json_ok($userInfo,200);

    }


    /**
     * 经销商列表
     * @Route("list", method="GET")
     * @Middleware({CheckAdmin::class})
     */
    public function list()
    {
        $uid = input('get.uid', '', 'int');
        if (empty($uid)) {
            return json_error(10002);
        }
        $role = $this->request->sys_user->role;
        $userM = new UserM();
        if ($role == 0) {//管理员
            $list = $userM->field(['id','account','user_name'])->select();
        } else
            $list = $userM->where('id',$uid)->whereOr('parent_id', $uid)->field(['id','account','user_name'])->select();

        return json_ok(['list' => $list, 'count' => count($list)], 200);
    }
}
